package com.charlotte.study.gupao;

import java.util.concurrent.TimeUnit;

/**
 * @author junjie.ding
 * @data 2021/11/23
 * @description
 */
public class InterruptThreadDemo {
    private static int i = 0;

    public static void main(String[] args) throws InterruptedException{

        // 循环线程
        MyThread myThread = new MyThread();
        myThread.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("执行中断！");
        myThread.interrupt();

        // 阻塞线程
        BlockedThread blockedThread = new BlockedThread();
        blockedThread.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("执行中断！");
        blockedThread.interrupt();
    }

    // 处于循环状态下的中断，通过while条件判断即可
    static class MyThread extends Thread {
        @Override
        public void run() {
            while(!Thread.currentThread().isInterrupted()){
                i++;
                System.out.println(i);
            }
        }
    }

    // 处于阻塞状态的线程收到中断信号，会抛出异常
    static class BlockedThread extends Thread {
        @Override
        public void run() {
            while(!Thread.currentThread().isInterrupted()){
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    // 收到中断信号，会执行这里，而不是直接根据Thread.currentThread().isInterrupted()来直接决定中断
                    //
                    System.out.println("接收到中断信号后，捕获到异常！");
                    e.printStackTrace();
                    // 线程自己决定是否要真的中断
                    Thread.currentThread().interrupt();// 如果这个不执行，当前线程的中断标志会重置，interrupted值会重置为false
                }
            }
        }
    }
}
